package com.example.csetpp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.csetpp.constants.MessageConstant;
import com.example.csetpp.exception.BaseException;
import com.example.csetpp.exception.OssFileOperateException;
import com.example.csetpp.mapper.RichTextMapper;
import com.example.csetpp.pojo.dto.richText.ChangeRichTextDTO;
import com.example.csetpp.pojo.dto.richText.DeleteRichText;
import com.example.csetpp.pojo.dto.richText.SaveRichTextDTO;
import com.example.csetpp.pojo.dto.user.UserLoginDTO;
import com.example.csetpp.pojo.entity.RichText;
import com.example.csetpp.pojo.vo.UserLoginVO;
import com.example.csetpp.service.RichTextService;
import com.example.csetpp.service.UserService;
import com.example.csetpp.utils.AliOSSUtils;
import com.example.csetpp.utils.Result;
import com.example.csetpp.utils.SnowFlakeID;
import com.example.csetpp.utils.UserIdHolder;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RichTextServiceImpl extends ServiceImpl<RichTextMapper, RichText> implements RichTextService {

    @Autowired
    private UserService userService;
    @Autowired
    private RichTextMapper richTextMapper;
    @Autowired
    private AliOSSUtils aliOSSUtils;

    @Override
    public Result saveRichText(SaveRichTextDTO saveRichTextDTO) {

        List<RichText> textInDataBase = query().eq("title", saveRichTextDTO.getTitle()).list();
        if(!textInDataBase.isEmpty())
        {
            return Result.error(MessageConstant.RICH_TEXT_TITLE_IS_EXIST);
        }
        //保存富文本
        RichText richText = new RichText();
        richText.setTitle(saveRichTextDTO.getTitle());
        richText.setContent(saveRichTextDTO.getContent());

        // 设置创建时间和更新时间为当前时间戳
        long currentTime = System.currentTimeMillis();
        richText.setCreateTime(currentTime);
        richText.setRank(0);
        richText.setId(SnowFlakeID.getSnowflakeId());
        save(richText);
        log.info("Rich text saved successfully for userId: {}", UserIdHolder.getCurrentId().intValue());
        return Result.success();
    }

    @Override
    public Result getTextByTitle(String email , String password,  String title) {
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        userLoginDTO.setAccount(email);
        userLoginDTO.setPassword(password);
        UserLoginVO userLoginVO = userService.login(userLoginDTO);
        List<RichText> richTexts = query().eq("title", title).list();
        if(richTexts.isEmpty())
        {
            return Result.error(MessageConstant.RICH_TEXT_NOT_EXIST);
        }
        return Result.success(richTexts.get(0));
    }

    @Override
    @Transactional
    public Result changeRichText(ChangeRichTextDTO changeRichTextDTO) {

        QueryWrapper<RichText> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", changeRichTextDTO.getTitle());
        RichText richText = richTextMapper.selectOne(queryWrapper);

        String oldContent = richText.getContent();
        String newContent = changeRichTextDTO.getContent();

        Set<String> oldSet = extractMediaUrls(oldContent);
        Set<String> newSet = extractMediaUrls(newContent);

        log.info("oldSet = {}", oldSet);
        log.info("newSet = {}", newSet);

        //获取需要删除的链接
        Set<String> urlsToDelete = new HashSet<>(oldSet);
        urlsToDelete.removeAll(newSet);

        //删除OSS上的存储
        try {
            for (String url : urlsToDelete) {
                aliOSSUtils.deleteFile(url, MessageConstant.DELETE_OSS_FILE_IN_URL);
            }
        } catch (Exception e) {
            throw new OssFileOperateException("OSS文件删除异常");
        }

        //更新数据库
        updateById(
                RichText.builder()
                        .id(richText.getId())
                        .content(newContent)
                        .build()
        );

        return Result.success();
    }

    @Override
    public Result deleteRichText(DeleteRichText deleteRichText) {
        try {
            removeById(deleteRichText.getId());
        } catch (Exception e) {
            throw new BaseException("删除富文本出错");
        }
        return Result.success();
    }

    @Override
    public Result getAll() {
        List<RichText> richTextList = list();
        return Result.success(richTextList);
    }


    //获取content里的图片/视频链接
    private Set<String> extractMediaUrls(String htmlContent) {
        if (!StringUtils.hasText(htmlContent)) {
            return new HashSet<>();
        }

        Document doc = Jsoup.parse(htmlContent);
        // 提取所有图片的src
        Elements imgTags = doc.select("img[src]");
        Set<String> imageUrls = imgTags.stream()
                .map(element -> element.attr("src").trim()) // <-- 加上 .trim()
                .collect(Collectors.toSet());
        // 提取所有视频的src
        Elements videoTags = doc.select("video > source[src]");
        Set<String> videoUrls = videoTags.stream()
                .map(element -> element.attr("src").trim()) // <-- 这里也加上 .trim()
                .collect(Collectors.toSet());

        // 合并并返回
        Set<String> allUrls = new HashSet<>(imageUrls);
        allUrls.addAll(videoUrls);

        // 过滤掉非OSS的URL，例如base64编码的图片或外部链接
        String ossUrlPrefix = "https://predict-bucket2.oss-cn-guangzhou.aliyuncs.com/";
        return allUrls.stream()
                .filter(url -> url.startsWith(ossUrlPrefix))
                .collect(Collectors.toSet());
    }
}